import {BaseService} from "../base/BaseService";
import type {AxiosRequestConfig} from "axios";
import axios from "axios";
import {BaseCommand} from "../base/BaseCommand";

export class VCairnService extends BaseService {
    private static _defaults: AxiosRequestConfig = {};
    static get defaults() { return VCairnService._defaults; }
    static set defaults(value: AxiosRequestConfig) {
        VCairnService._defaults = Object.assign({}, VCairnService._defaults, value);
    }

    private readonly _axios;

    constructor(cmd:BaseCommand) {
        super(cmd);
        this._axios = axios.create(
            Object.assign({},VCairnService.defaults)
        );
    }

    send(options:AxiosRequestConfig) {
        const cmd = (this.cmd as BaseCommand);
        const promise = this._axios(options);
        promise.then((response) => {
            cmd.serverSuccess(response);
        }).catch(error => {
            if (error.response) {
                cmd.serverError(error);
            } else if (error.request) {
                cmd.noResponse(error);
            } else {
                cmd.noSend(error);
            }
        }).finally(() => {
            cmd.onFinally();
        });
    }
}